package com.atguigu.yygh.email.controller;

import com.atguigu.yygh.common.result.Result;
import com.atguigu.yygh.email.service.EmailService;
import com.atguigu.yygh.email.utils.RandomUtil;

import java.util.concurrent.TimeUnit;
import javax.annotation.Resource;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/api/email")
public class EmailApiController {

    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    @Resource
    private EmailService emailService;

    //发送验证码到邮箱
    @GetMapping("send/{email}")
    public Result sendCode(@PathVariable String email) {
        //从redis获取验证码，如果获取获取到，返回ok
        // key 手机号  value 验证码
        String code = (String) redisTemplate.opsForValue().get(email);
        if (!StringUtils.isEmpty(code)) {
            return Result.ok();
        }
        //如果从redis获取不到，
        // 生成验证码，
        code = RandomUtil.getSixBitRandom();

        //生成验证码放到redis里面，设置有效时间
        emailService.send(email, code);
        redisTemplate.opsForValue().set(email, Integer.parseInt(code), 2, TimeUnit.MINUTES);
        return Result.ok();
    }


}
